﻿import { useState, useRef } from "react"

interface RecordingTabProps {
  onInsertToEditor: (imageSrc: string, altText: string) => void
}

export default function RecordingTab({ onInsertToEditor }: RecordingTabProps) {
  const [isRecording, setIsRecording] = useState(false)
  const [recording, setRecording] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [recordingTime, setRecordingTime] = useState(0)
  
  const mediaRecorderRef = useRef<MediaRecorder | null>(null)
  const streamRef = useRef<MediaStream | null>(null)
  const chunksRef = useRef<Blob[]>([])
  const timerRef = useRef<NodeJS.Timeout | null>(null)

  // 开始录屏
  const startRecording = async () => {
    try {
      setIsRecording(true)
      setError(null)
      setRecordingTime(0)
      chunksRef.current = []

      // 请求屏幕录制权限
      const stream = await navigator.mediaDevices.getDisplayMedia({
        video: {
          mediaSource: 'screen',
          width: { ideal: 1920 },
          height: { ideal: 1080 },
          frameRate: { ideal: 30 }
        } as any,
        audio: {
          echoCancellation: true,
          noiseSuppression: true,
          sampleRate: 44100
        }
      })

      streamRef.current = stream

      // 创建 MediaRecorder
      const mediaRecorder = new MediaRecorder(stream, {
        mimeType: 'video/webm;codecs=vp9'
      })
      mediaRecorderRef.current = mediaRecorder

      // 处理录制数据
      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          chunksRef.current.push(event.data)
        }
      }

      // 录制停止时处理
      mediaRecorder.onstop = () => {
        const blob = new Blob(chunksRef.current, { type: 'video/webm' })
        const videoUrl = URL.createObjectURL(blob)
        setRecording(videoUrl)
        
        // 清理资源
        if (streamRef.current) {
          streamRef.current.getTracks().forEach(track => track.stop())
          streamRef.current = null
        }
      }

      // 开始录制
      mediaRecorder.start(1000) // 每秒收集一次数据

      // 开始计时
      timerRef.current = setInterval(() => {
        setRecordingTime(prev => prev + 1)
      }, 1000)

      // 监听用户停止屏幕共享
      stream.getVideoTracks()[0].onended = () => {
        stopRecording()
      }

    } catch (err) {
      console.error('录屏失败:', err)
      setError(err instanceof Error ? err.message : "录屏失败，请检查权限设置")
      setIsRecording(false)
    }
  }

  // 停止录屏
  const stopRecording = () => {
    if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
      mediaRecorderRef.current.stop()
    }
    
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(track => track.stop())
      streamRef.current = null
    }

    if (timerRef.current) {
      clearInterval(timerRef.current)
      timerRef.current = null
    }

    setIsRecording(false)
  }

  // 下载录屏
  const downloadRecording = () => {
    if (!recording) return

    const link = document.createElement("a")
    link.download = `recording-${new Date().toISOString().slice(0, 19).replace(/:/g, "-")}.webm`
    link.href = recording
    link.click()
  }

  // 清除录屏
  const clearRecording = () => {
    if (recording) {
      URL.revokeObjectURL(recording)
    }
    setRecording(null)
    setError(null)
    setRecordingTime(0)
  }

  // 插入录屏到编辑器
  const insertRecordingToEditor = () => {
    if (recording) {
      onInsertToEditor(recording, "录屏视频")
    }
  }

  // 格式化录制时间
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  return (
    <div>
      <h3 style={{ marginTop: 0, color: "#333" }}>
         录屏工具
      </h3>
      
      <div style={{ marginBottom: 16 }}>
        <button
          onClick={isRecording ? stopRecording : startRecording}
          style={{
            width: "100%",
            padding: "12px",
            backgroundColor: isRecording ? "#dc3545" : "#007bff",
            color: "white",
            border: "none",
            borderRadius: "6px",
            fontSize: "14px",
            cursor: "pointer",
            marginBottom: "8px"
          }}>
          {isRecording ? `停止录屏 (${formatTime(recordingTime)})` : "开始录屏"}
        </button>
        
        {isRecording && (
          <div style={{
            textAlign: "center",
            fontSize: "12px",
            color: "#666",
            marginBottom: "8px"
          }}>
            <div style={{
              display: "inline-block",
              width: "8px",
              height: "8px",
              backgroundColor: "#dc3545",
              borderRadius: "50%",
              marginRight: "6px",
              animation: "blink 1s infinite"
            }}></div>
            录制中...
          </div>
        )}
      </div>

      {error && (
        <div
          style={{
            padding: "8px",
            backgroundColor: "#f8d7da",
            color: "#721c24",
            borderRadius: "4px",
            marginBottom: "12px",
            fontSize: "12px"
          }}>
           {error}
        </div>
      )}

      {recording && (
        <div style={{ marginTop: 16 }}>
          <div style={{ marginBottom: 8 }}>
            <video
              src={recording}
              controls
              style={{
                width: "100%",
                maxHeight: "150px",
                border: "1px solid #ddd",
                borderRadius: "4px"
              }}
            />
          </div>
          
          <div style={{ display: "flex", gap: "8px", marginBottom: 8 }}>
            <button
              onClick={downloadRecording}
              style={{
                flex: 1,
                padding: "8px",
                backgroundColor: "#28a745",
                color: "white",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                cursor: "pointer"
              }}>
               下载
            </button>
            
            <button
              onClick={insertRecordingToEditor}
              style={{
                flex: 1,
                padding: "8px",
                backgroundColor: "#17a2b8",
                color: "white",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                cursor: "pointer"
              }}>
               插入到编辑器
            </button>
            
            <button
              onClick={clearRecording}
              style={{
                flex: 1,
                padding: "8px",
                backgroundColor: "#6c757d",
                color: "white",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                cursor: "pointer"
              }}>
               清除
            </button>
          </div>
        </div>
      )}

      <div style={{ marginTop: 12, fontSize: '11px', color: '#666' }}>
         提示：点击"开始录屏"后，选择要录制的屏幕或窗口
      </div>

      {/* 添加闪烁动画 */}
      <style>{`
        @keyframes blink {
          0%, 50% { opacity: 1; }
          51%, 100% { opacity: 0.3; }
        }
      `}</style>
    </div>
  )
}
